package com.fenfen.novel.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.fenfen.novel.ChapterActivity;
import com.fenfen.novel.R;
import com.fenfen.novel.model.Chapter;
import com.fenfen.novel.rest.RestClient;
import com.fenfen.novel.utils.CommonUtil;
import com.fenfen.novel.utils.NovelFileCallbackListener;
import com.fenfen.novel.utils.NovelFileUtils;
import com.fenfen.novel.utils.SharedPrefsUtils;

import org.parceler.Parcels;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ChapterFragment extends Fragment {
  public static final String BUNDLE_POS = "position";

  public static final String STATE_POS = "scroll_pos";

  private static String Tag = ChapterFragment.class.getSimpleName();

  private TextView chapterContent;
  private int chapterOrder;
  private int currentPos = CommonUtil.NONE_INT_DATA;

  private TextView titleTv;
  private TextView timeTv;
  private TextView progressTv;
  private TextView batteryTv;

  private String chapterTitle;

  private BroadcastReceiver timeChangeReceiver;
  private BroadcastReceiver batteryStateReceiver;

  private CommonUtil.CallbackListener mCallbackListener;

  //if chapter content data load complete and success
  private byte dataLoadStatus = CommonUtil.DATA_STATUS.NOT_START;

  private ScrollView scroller;
  private int scrollY; //scroller滑动距离
  private Chapter chapter;

  public static Fragment newInstance(Bundle bundle) {
    ChapterFragment fragment = new ChapterFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    chapterOrder = getArguments().getInt(BUNDLE_POS) + 1;
  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_POS, scroller.getScrollY());
  }

  @Override
  public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);
    if (savedInstanceState != null) {
      scrollY = savedInstanceState.getInt(STATE_POS);
    }
  }

  public void chapterScrollToPos() {
    if (scrollY != CommonUtil.ZERO_INT_DATA) {
      scroller.post(new Runnable() {
        @Override
        public void run() {
          scroller.scrollTo(0, scrollY);
        }
      });
    }
  }

  private void setBatteryInfo(Intent battery) {
    if (getActivity() != null) {
      int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);

      batteryTv.setText(String.valueOf(level));
    }
  }

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_chapter, container, false);
    chapterContent = (TextView) view.findViewById(R.id.chapter_content);
    titleTv = (TextView) view.findViewById(R.id.chapter_inner_title);
    progressTv = (TextView) view.findViewById(R.id.chapter_progress);

    timeTv = (TextView) view.findViewById(R.id.current_time);
    batteryTv = (TextView) view.findViewById(R.id.battery_info);

    scroller = (ScrollView) view.findViewById(R.id.scroller);

    int textSize = SharedPrefsUtils.getInstance(getActivity()).getChapterTextSize();
    setChapterTextSize(textSize);
    chapterContent.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
//        Snackbar.make(v, "click tv", Snackbar.LENGTH_SHORT).show();
        boolean isShow = ((ChapterActivity) getActivity()).getFullScreenIsShowing();
        ((ChapterActivity) getActivity()).toggleFullScreenUI(!isShow);
      }
    });
    initIntentData();

    this.mCallbackListener = ((ChapterActivity) getActivity()).getCallbackListener();

    if (isDownload) {
      //load from txt
      loadChapterFromLocal();
    } else {
      loadChapter();
    }
    return view;
  }

  @Override
  public void onResume() {
    super.onResume();
    registerTimeAndBatteryRecevier();
  }

  @Override
  public void onPause() {
    super.onPause();
    unregisterTimeAndBatteryRecevier();
  }

  private void unregisterTimeAndBatteryRecevier() {
    if (timeChangeReceiver != null) {
      getActivity().unregisterReceiver(timeChangeReceiver);
    }
    if (batteryStateReceiver != null) {
      getActivity().unregisterReceiver(batteryStateReceiver);
    }
  }

  private void registerTimeAndBatteryRecevier() {
    timeChangeReceiver = new TimeChangeReceiver();
    IntentFilter timeIntentFilter = new IntentFilter();
    timeIntentFilter.addAction(Intent.ACTION_TIME_CHANGED);
    timeIntentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
    timeIntentFilter.addAction(Intent.ACTION_TIME_TICK);
    getActivity().registerReceiver(timeChangeReceiver, timeIntentFilter);

    batteryStateReceiver = new BatteryStateReceiver();
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = getActivity().registerReceiver(batteryStateReceiver, ifilter);

    //initFirst
    setTimeInfo();
    setBatteryInfo(batteryStatus);
  }

  private void setTimeInfo() {
    if (getActivity() != null) {
      String currentTime = CommonUtil.getCurrentHourMinutes();
      timeTv.setText(currentTime);
    }
  }

  private int novelId;
  private int chapterCount;

  private boolean isDownload;
  private String novelPath;

  //  private int chapterCount;
  private void initIntentData() {
    Chapter chapter = Parcels.unwrap(getActivity().getIntent().getParcelableExtra(ChapterActivity.EXTRA_CHAPTER));
    chapterCount = getActivity().getIntent().getIntExtra(ChapterActivity.EXTRA_CHAPTER_COUNT, CommonUtil.NONE_INT_DATA);
    novelId = chapter.getNovelId();

    isDownload = ((ChapterActivity) getActivity()).getDownloadStatus();
    novelPath = CommonUtil.getNovelFilePath(getActivity(), novelId);
  }

  private boolean isCurrentShown() {
    return currentPos + 1 == chapterOrder && getActivity() != null;
  }

  public byte getDataLoadStatus() {
    return dataLoadStatus;
  }

  public void setDataLoadStatus(byte dataLoadStatus) {
    this.dataLoadStatus = dataLoadStatus;
  }

  public void loadChapterFromLocal() {
    NovelFileUtils.getInstance().getFileChapterContent(novelPath, chapterOrder, new NovelFileCallbackListener() {
      @Override
      public void onChapterContentFinish(final String content, final String title) {
        super.onChapterContentFinish(content, title);
        final String costTime = getCost();
        getActivity().runOnUiThread(new Runnable() {
          @Override
          public void run() {
            if (!TextUtils.isEmpty(costTime)) {
              CommonUtil.showSnack(chapterContent, String.format(getString(R.string.cost_time), costTime));
            }
            if (TextUtils.isEmpty(content)) {
              setDataLoadStatus(CommonUtil.DATA_STATUS.NO_DATA);
              if (isCurrentShown()) {
                mCallbackListener.onFailure();
              }
              return;
            }
            chapterContent.setText(content);
            setDataLoadStatus(CommonUtil.DATA_STATUS.SUCCESS);
            Chapter chapter = new Chapter();
            chapter.setChapterOrder(chapterOrder);
            chapter.setNovelId(novelId);
            chapter.setId(-1);
            chapter.setChapterContent(content);
            chapter.setChapterTitle(title);
            setChapter(chapter);
            chapterTitle = title;
            setChapterTitle(chapterTitle);
            setChapterProgress(chapterOrder);
            if (isCurrentShown()) {
              mCallbackListener.onResponse();
            }
          }
        });
      }
    });
  }

  public void loadChapter() {
//    int chapterId = chapter.getId();
    Call<List<Chapter>> call = RestClient.newInstance().getNovelService().showNovelChapterByOrder(novelId, chapterOrder);
    setDataLoadStatus(CommonUtil.DATA_STATUS.REQUEST);
    call.enqueue(new Callback<List<Chapter>>() {
      @Override
      public void onResponse(Call<List<Chapter>> call, Response<List<Chapter>> response) {
        List<Chapter> chapters = response.body();
        if (!response.isSuccessful() || chapters == null || chapters.size() == 0) {
          chapterContent.setText(getString(R.string.no_chapter_content));
          setDataLoadStatus(CommonUtil.DATA_STATUS.NO_DATA);
          if (isCurrentShown()) {
            mCallbackListener.onFailure();
          }
          return;
        }
        setDataLoadStatus(CommonUtil.DATA_STATUS.SUCCESS);
        Chapter chapter = response.body().get(0);
        setChapter(chapter);
        chapterContent.setText(chapter.getChapterContent());
        chapterTitle = chapter.getChapterTitle();
        setChapterTitle(chapterTitle);
        setChapterProgress(chapter.getChapterOrder());
        if (isCurrentShown()) {
          mCallbackListener.onResponse();
        }
      }

      @Override
      public void onFailure(Call<List<Chapter>> call, Throwable t) {
        if (isCurrentShown()) {
          mCallbackListener.onFailure();
        }
        setDataLoadStatus(CommonUtil.DATA_STATUS.FAIL);
      }
    });
  }

  public void setChapterProgress(int progress) {
    if (getActivity() != null) {
      progressTv.setText(String.format(getString(R.string.chapter_progress), progress, chapterCount));
    }
  }

  public void setChapterTitle(String title) {
    if (getActivity() != null) {
      titleTv.setText(title);
    }
  }

  public String getChapterTitle() {
    Log.d("init", "currentPos=" + currentPos + ",chapterOrder=" + chapterOrder);
    if (isCurrentShown() && titleTv != null) {
      Log.d("init", "titletv.string=" + titleTv.getText().toString());
      return titleTv.getText().toString();
    }
    return null;
  }

  public void setChapterTextSize(int size) {
    if (chapterContent != null) {
      chapterContent.setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
    }
  }

  public int getChapterTextSize() {
    return (int) CommonUtil.px2Sp(getActivity(), chapterContent.getTextSize());
  }

  public void setCurrentPos(int currentPos) {
    this.currentPos = currentPos;
  }

  public void setChapter(Chapter chapter) {
    this.chapter = chapter;
  }

  public Chapter getChapter() {
    return this.chapter;
  }

  private class TimeChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if (action.equals(Intent.ACTION_TIME_CHANGED) ||
          action.equals(Intent.ACTION_TIMEZONE_CHANGED) ||
          action.equals(Intent.ACTION_TIME_TICK)) {
        setTimeInfo();
      }
    }
  }

  private class BatteryStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
        setBatteryInfo(intent);
      }
    }
  }
}
